package com.fang.transfer.file.client.gui;

import com.fang.transfer.file.client.AppContext;
import com.fang.transfer.file.client.util.UnitConversionUtil;
import com.fang.transfer.file.common.code.ClientSendCode;
import com.fang.transfer.file.common.model.TransferFileRequest;
import com.fang.transfer.file.common.model.User;
import lombok.Getter;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.*;
import java.util.Collection;
import java.util.Vector;

public class GUI {

    public static final int frameWidth = 500;
    public static final int frameHeight = 400;

    private JFrame frame;
    private JDialog dialog;

    /**
     * 接收文件提示框
     */
    private JTextField fileInfo;

    /**
     * 需要上传文件路径
     */
    private final JTextArea filePath = new JTextArea(2, 38);

    /**
     * 需要确认传输的文件
     */
    private TransferFileRequest transferFileRequest;

    /**
     * 在线用户
     */
    private JPanel onlineUser;

    /**
     * 服务器地址输入框
     */
    @Getter
    private final JTextField hostText = new JTextField();

    public void init() {
        initFrame();
    }

    private void initFrame() {
        //创建窗体对象
        frame = new JFrame();
        //创建窗体对象，并设置窗体标题为zfliu，和f.setTitle("zfliu96");方法功能相同
        //Frame f=new Frame("zfliu");

        //设置窗体大小
//        frame.setSize(800, 400);

        //设置窗体位置
        frame.setLocation(200, 300);

        //可以直接设置窗体的位置和大小
        //f.setBounds(200, 300, 800, 400);

        //设置窗体名字
        frame.setTitle("文件传输");

        //设置窗体是否可见，先设置好窗体的属性再将其显示出来
        frame.setVisible(true);
        frame.setBackground(Color.blue);
        //关闭窗体
        //事件源：f
        //事件：对窗体进行处理
        //事件处理：关闭窗口（System.exit(0)）；需要实现WindowListener接口，并重写关闭窗口的方法
        //事件监听
        //使用适配器模式，只需要重写需要用的方法即可，WindowAdapter适配器类
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                AppContext.transferService.close();
            }
        });

        //接收文件提示框
        initDialog();

    }

    private void initDialog() {
        this.dialog = new JDialog(frame, "接收文件");
        dialog.setLayout(new FlowLayout());
        dialog.setSize(300, 200);
        dialog.setLocation(500, 500);
        dialog.setModal(true);
        fileInfo = new JTextField(25);
        JButton ok = new JButton("接收");
        JButton no = new JButton("拒绝");
        dialog.add(fileInfo);
        dialog.add(ok);
        dialog.add(no);

        ok.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                AppContext.transferService.receiveFile(transferFileRequest);
                dialog.setVisible(false);
            }

        });
        no.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                dialog.setVisible(false);
            }
        });
    }

    public void connectionServiceUI() {
        JPanel panel = new JPanel();

        panel.setLayout(new FlowLayout(3));
//        panel.setLayout(new BorderLayout());
        int height = 80;
        panel.setSize(660, height);
        final JTextField userNameText = new JTextField();
        userNameText.setColumns(4);
        userNameText.setText("张三");
        userNameText.setFont(new Font(null, 0, 20));

        hostText.setText("139.196.203.177:8888");
//        hostText.setText("127.0.0.1:8888");
        hostText.setFont(new Font(null, 0, 20));
        JButton connectionButton = new JButton("开始连接");
        connectionButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                String text = hostText.getText();
                String[] split = text.split(":");
                try {
                    AppContext.transferService.connectionService(split[0], Integer.parseInt(split[1]), userNameText.getText());
                } catch (InterruptedException interruptedException) {
                    interruptedException.printStackTrace();
                }
            }
        });
        panel.add(hostText);
        panel.add(userNameText);
        panel.add(connectionButton);
        connectionButton.setSize(100, height);
        frame.setContentPane(panel);
        frame.setSize(460, height);
    }


    public void homeUI() {
        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout(FlowLayout.LEFT, 2, 2));


        //在线用户
        panel.add(onlineUser());
        //发送文件面板
        panel.add(initSendUI());
        //发送文件拖入文件面板
        panel.add(initSendDragUI());
        frame.setContentPane(panel);
        frame.setSize(frameWidth, frameHeight);

    }

    private Component initSendDragUI() {
        JPanel result = new JPanel();
        result.setMaximumSize(new Dimension(frameWidth, 50));
        result.setBackground(new java.awt.Color(255, 160, 122));
        result.setLayout(new BorderLayout());
        result.setBorder(new EmptyBorder(1, 1, 1, 1));
        JLabel label = new JLabel("拖动文件到此处");
        label.setFont(new Font(Font.DIALOG, Font.PLAIN, 70));
        label.setMaximumSize(new Dimension(frameWidth, 50));

        result.add(label);
        result.setTransferHandler(new TransferHandler() {
            @Override
            public boolean importData(JComponent comp, Transferable t) {
                try {
                    java.util.List fileList = (java.util.List) t.getTransferData(DataFlavor.javaFileListFlavor);
                    filePath.setText(fileList.get(0).toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return false;
            }

            @Override
            public boolean canImport(JComponent comp, DataFlavor[] flavors) {
                for (int i = 0; i < flavors.length; i++) {
                    if (DataFlavor.javaFileListFlavor.equals(flavors[i])) {
                        return true;
                    }
                }
                return false;
            }
        });
        return result;
    }

    private JPanel initSendUI() {
        JPanel result = new JPanel();
        onlineUser.setLayout(new GridLayout(1, 2));
        final JButton sendBut = new JButton("发送");
        filePath.setEditable(false);
        JScrollPane jScrollPane = new JScrollPane(filePath);
        result.add(jScrollPane);
        result.add(sendBut);

        sendBut.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                JComboBox jComboBox = (JComboBox) onlineUser.getComponent(0);
                User user = (User) jComboBox.getSelectedItem();
                String text = filePath.getText();
                AppContext.transferService.sendFile(user, text);
            }
        });
        return result;
    }

    private Component onlineUser() {
        this.onlineUser = new JPanel();
        onlineUser.setLayout(new GridLayout(1, 2, 1, 3));
        final JComboBox jComboBox = new JComboBox();
        AppContext.tcpUtil.writeAndFlush(ClientSendCode.GET_ALL_USER);
        JButton getUser = new JButton("刷新在线用户");
        onlineUser.add(jComboBox);
        onlineUser.add(getUser);
        getUser.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                AppContext.tcpUtil.writeAndFlush(ClientSendCode.GET_ALL_USER);
            }
        });
        return onlineUser;
    }


    public void isReceiveFileUI(TransferFileRequest transferFileRequest) {
        this.transferFileRequest = transferFileRequest;
        Long length = transferFileRequest.getLength();
        String size = UnitConversionUtil.getPrintSize(length);
        fileInfo.setText("传输人:" + transferFileRequest.getSendUser().getName() + "  文件名:" + transferFileRequest.getName() + " 大小:" + size);
        dialog.setVisible(true);
    }


    public void diaLogInfo(String msg) {
        final JDialog dialogInfo = new JDialog(frame, "提示");
        dialogInfo.setLayout(new FlowLayout());
        dialogInfo.setSize(300, 200);
        dialogInfo.setLocation(500, 500);
        dialogInfo.setModal(true);
        JTextField text = new JTextField(60);
        text.setText(msg);
        JButton ok = new JButton("确定");
        dialogInfo.add(text);
        dialogInfo.add(ok);

        ok.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dialogInfo.setVisible(false);
            }
        });
    }

    public void onlineUserUpdate(Collection<User> onlineUserList) {
        onlineUser.remove(0);
        Vector<User> users = new Vector<>(onlineUserList);
        final JComboBox jComboBox = new JComboBox(users);
        onlineUser.add(jComboBox, 0);
        onlineUser.updateUI();
    }
}
